﻿using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Geometry = Esri.ArcGISRuntime.Geometry.Geometry;

namespace classTest
{
    /// <summary>
    /// BufferGeometryWindow.xaml 的交互逻辑
    /// </summary>
    public partial class BufferGeometryWindow : Window
    {
        private GraphicsOverlay bufferGraphicsOverlay = new GraphicsOverlay();
        private MapView MyMapView { set; get; }
        private List<Feature> FeatureQuery { set; get; }
        private FeatureLayer _layer;
        private BufferLayerInfoWindow bliw;
        public BufferGeometryWindow(MapView mapView1, List<Feature> FeatureQuery1)
        {
            InitializeComponent();
            MyMapView = mapView1;
            FeatureQuery = FeatureQuery1;
            //初始化数据
            Initialize();
        }

        private void Initialize()
        {
            List<ComboBoxItem> layerItem1 = new List<ComboBoxItem>();
            List<ComboBoxItem> layerItem2 = new List<ComboBoxItem>();
            LayerCollection pLayers = MyMapView.Map.OperationalLayers;
            //for循环地图业务图层的所有图层名称与参数进行比对，一旦匹配到相等即返回对应图层
            for (int i = pLayers.Count - 1; i >= 0; i--)
            {
                ComboBoxItem cbi1 = new ComboBoxItem();
                cbi1.Content = pLayers[i].Name;
                cbi1.DataContext = pLayers[i];
                layerItem1.Add(cbi1);
                ComboBoxItem cbi2 = new ComboBoxItem();
                cbi2.Content = pLayers[i].Name;
                cbi2.DataContext = pLayers[i];
                layerItem2.Add(cbi2);

            }
            inputLayerComboBox.ItemsSource = layerItem1;
            analysisLayerComboBox.ItemsSource = layerItem2;

            if (FeatureQuery!=null && FeatureQuery.Count>0)
            {
                ComboBoxItem cbi3 = new ComboBoxItem();
                cbi3.Content = "当前所选或要素图层";
                layerItem1.Insert(0, cbi3);
                inputLayerComboBox.SelectedIndex = 0;
            }
        }

        private Geometry resultGeometry;
        private FeatureQueryResult pQueryResult2;
        private async void Buffer_Analysis()
        {
            if (inputLayerComboBox.SelectedIndex == -1) return;
            try
            {
                _layer.ClearSelection();
            }
            catch
            {

            }
            if (pQueryResult2 != null && pQueryResult2.Count() > 0) pQueryResult2 = null;
            try
            {
                Convert.ToDouble(distanceTextBox.Text);
            }
            catch
            {
                MessageBox.Show("距离是数字，不要输入其它的东东");
                return;
            }

            List<double> distances = new List<double>();
            List<Geometry> geometries = new List<Geometry>();
            
            if (FeatureQuery.Count>0 && inputLayerComboBox.SelectedIndex==0)
            {
                double distance = Convert.ToDouble(distanceTextBox.Text);
                foreach (Feature f in FeatureQuery)
                {
                    Console.WriteLine(f.FeatureTable.TableName);
                    geometries.Add(f.Geometry);
                    distances.Add(distance);
                }
            }
            else
            {
                FeatureLayer layer = (inputLayerComboBox.SelectedItem as ComboBoxItem).DataContext as FeatureLayer;
                QueryParameters pQueryP = new QueryParameters();
                FeatureQueryResult pQueryResult = await layer.FeatureTable.QueryFeaturesAsync(pQueryP);
                double distance = Convert.ToDouble(distanceTextBox.Text);
                foreach (Feature f in pQueryResult)
                {
                    geometries.Add(f.Geometry);
                    distances.Add(distance);
                }
            }

            IEnumerable<Geometry> result = GeometryEngine.Buffer(geometries, distances, true);
            if (result.Count() == 0)
            {
                MessageBox.Show("缓冲结果集为空");
                return;
            }
            Graphic g = new Graphic(result.First(), new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, System.Drawing.Color.FromArgb(125, 255, 250, 0), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Black, 1.0)));
            MyMapView.GraphicsOverlays[0].Graphics.Add(g);

            if (analysisLayerComboBox.SelectedIndex != -1)
            {
                _layer = (analysisLayerComboBox.SelectedItem as ComboBoxItem).DataContext as FeatureLayer;
                QueryParameters pQueryP2 = new QueryParameters();
                pQueryP2.Geometry = result.First();
                pQueryP2.SpatialRelationship = SpatialRelationship.Intersects;

                try
                {
                    pQueryResult2 = await _layer.SelectFeaturesAsync(pQueryP2, Esri.ArcGISRuntime.Mapping.SelectionMode.New);
            }
                catch
            {
                //pQueryResult2 = await layer2.FeatureTable.QueryFeaturesAsync(pQueryP2);
                MessageBox.Show("Not implemented: operation does not support curves yet");
            }

        }
            
            resultGeometry = result.First();

            bliw = new BufferLayerInfoWindow(resultGeometry, pQueryResult2, MyMapView);
            bliw.Show();
            bliw.Activate();
        }

        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            Buffer_Analysis();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            //清理几何图层
            if (MyMapView.GraphicsOverlays[0].Graphics.Count > 0)
                MyMapView.GraphicsOverlays[0].Graphics.RemoveAt(MyMapView.GraphicsOverlays[0].Graphics.Count - 1);
            //取消选择的图层
            if (analysisLayerComboBox.SelectedIndex !=-1)
            {
                FeatureLayer layer2 = (analysisLayerComboBox.SelectedItem as ComboBoxItem).DataContext as FeatureLayer;
                layer2.ClearSelection();
            }

        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if(bliw!=null)bliw.Close();
        }
    }
}
